package com.example.diarymanger.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.diarymanger.bean.ApiResponse;
import com.example.diarymanger.bean.NoteBean;
import com.example.diarymanger.mapper.NoteMapper;
import com.example.diarymanger.service.NoteService;
import com.example.diarymanger.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Service
public class NoteServiceImpl extends ServiceImpl<NoteMapper, NoteBean> implements NoteService {

    @Autowired
    private NoteMapper noteMapper;
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    /**
     * 保存笔记
     *
     * @param noteBean
     * @return
     */
    @Override
    public ResponseEntity<ApiResponse> saveNote(NoteBean noteBean) {
        logger.info("Saving note with title: {}", noteBean.getNoteTitle());
        try {
            // 1. 自动处理标签转换（通过实体类的setTags方法）
            if (noteBean.getTags() != null) {
                noteBean.setTags(noteBean.getTags()); // 触发自动转换到tagsString
            } else {
                noteBean.setTagsString(""); // 确保tagsString有默认值
            }
            System.out.println("noteBean=" + noteBean);
            System.out.println("tagsString=" + noteBean.getTagsString());
            // 2. 生成ID
            Integer maxNoteId = noteMapper.selectMaxNoteId();
            noteBean.setNoteId((maxNoteId == null ? 10000 : maxNoteId) + 1);

            // 3. 保存数据（tagsString会自动存入数据库）
            int result = noteMapper.insert(noteBean);
            if (result > 0) {
                logger.info("笔记保存成功");
                return ResponseEntity.ok(new ApiResponse(true, "保存成功"));
            } else {
                logger.error("数据库插入失败");
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body(new ApiResponse(false, "保存失败"));
            }
        } catch (Exception e) {
            logger.error("保存出错", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(new ApiResponse(false, "系统错误: " + e.getMessage()));
        }
    }

    /**
     * 根据用户ID获取笔记列表
     * @param userId
     * @return
     */
    @Override
    public ResponseEntity<List<NoteBean>> getNotesByUserId(Long userId) {
        QueryWrapper<NoteBean> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", userId);
        List<NoteBean> noteList = noteMapper.selectList(wrapper);
        return ResponseEntity.ok(noteList);
    }

    /**
     * 根据笔记ID获取笔记
     * @param noteId
     * @return
     */
    @Override
    public NoteBean getNoteByNoteId(Integer noteId) {
        QueryWrapper<NoteBean> wrapper = new QueryWrapper<>();
        wrapper.eq("note_id", noteId);
        NoteBean noteBean = noteMapper.selectOne(wrapper);
        if (noteBean == null) {
            System.out.println("该笔记号对应的笔记没找到，noteId=[" + noteId + "]");
            return null;
        }
        return noteBean;
    }

    /**
     * 更新笔记
     * @param noteBean
     * @return
     */
    @Override
    public boolean updateNote(NoteBean noteBean) {
        QueryWrapper<NoteBean> wrapper = new QueryWrapper<>();
        wrapper.eq("note_id", noteBean.getNoteId());
        return this.update(noteBean, wrapper);
    }

    /**
     * 根据笔记ID删除笔记
     * @param noteId
     * @return
     */
    @Override
    public boolean deleteByNoteId(Integer noteId) {
        QueryWrapper<NoteBean> wrapper = new QueryWrapper<>();
        wrapper.eq("note_id", noteId);
        return remove(wrapper);
    }

    @Override
    public ResponseEntity<List<NoteBean>> getIsPublicNoteAll() {
        QueryWrapper<NoteBean> wrapper = new QueryWrapper<>();
        wrapper.eq("is_public", 1);
        return ResponseEntity.ok(noteMapper.selectList(wrapper));
    }

}




